package com.fs.controller;


import com.fs.constans.CacheConstants;
import com.fs.constans.Constants;
import com.fs.util.RedisCache;
import com.fs.vo.Meta;
import com.fs.vo.ResponseData;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

//    @Autowired
//    private ISysConfigService configService;
    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public ResponseData<Map<String,String>> getCode(HttpServletResponse response) throws IOException
    {
        ResponseData<Map<String,String>> responseData = new ResponseData<>();
        String capStr = "", code = "";
        BufferedImage image = null;

        // 数学计算型验证码
        String cap = captchaProducerMath.createText();
        String[] ca = cap.split("@");
        capStr = ca[0];
        code = ca[1];


        // 3. 存储验证码答案到Redis
        String uuid = UUID.randomUUID().toString();
        redisCache.setCacheObject(CacheConstants.CAPTCHA_CODE_KEY + uuid, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        // 4. 生成验证码图片
        image = captchaProducer.createImage(capStr);

        // 5. 将图片转换为字节数组
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        ImageIO.write(image, "jpg", os);

        // 6. 使用Base64编码字节数组
        String base64Img = java.util.Base64.getEncoder().encodeToString(os.toByteArray());


        // 7. 封装到AjaxResult中
        Map<String,String> map=new HashMap<>();
        map.put("img",base64Img);
        map.put("uuid",uuid);
        responseData.setData(map);
        Meta meta = new Meta(200,"操作成功");
        responseData.setMeta(meta);


        return responseData;

    }
}